/**
 * 
 */
package hu.gbalage.owlforms.xforms;

import hu.gbalage.owlforms.api.Field;
import hu.gbalage.owlforms.api.Form;
import hu.gbalage.owlforms.api.data.CompositeValue;
import hu.gbalage.owlforms.api.data.FieldData;
import hu.gbalage.owlforms.api.data.FieldValue;
import hu.gbalage.owlforms.api.data.FormData;
import hu.gbalage.owlforms.api.style.FieldTitleProvider;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * @author balage
 *
 */
public class FormDataPrinter {

	public Element toXHTML(Document doc, FormData data){
		Element root = doc.createElement("xhtml:div");
		root.setAttribute("class", "printed");
		
		Form form = data.getForm();
		Element title = doc.createElement("h1");
		title.setTextContent(form.getStyle().getFieldTitleProvider().getTitle(form));
		
		print(doc,data,root);
		
		return root;
	}
	
	private void print(Document doc, FormData what, Element where){
		Element root = doc.createElement("xhtml:div");
		root.setAttribute("class", "formdata");
		where.appendChild(root);
		
		for(Field f : what.getForm().getStyle().getFieldOrderProvider().orderFields(what.getForm().listFields())){
			print(doc,what.getData(f),where, what.getForm().getStyle().getFieldTitleProvider());
		}
	}
	
	private void print(Document doc, FieldData what, Element where, FieldTitleProvider titles){
		String title = titles.getTitle(what.getField());
		if (what.getField().isComplex()){
			Element h2 = doc.createElement("xhtml:h2");
			h2.setTextContent(title);
			where.appendChild(h2);
			for(FieldValue v : what.listValues()){
				CompositeValue value = v.asCompositeValue();
				print(doc,value.getCompositeData(),where);
			}
		}else{
			for(FieldValue v : what.listValues()){
				Element div = doc.createElement("xhtml:div");
				if (what.getField().isDerivative())
					div.setAttribute("class", "value derivative");
				else
					div.setAttribute("class", "value");
				where.appendChild(div);
				
				Element titlespan = doc.createElement("xhtml:span");
				titlespan.setAttribute("class", "title");
				titlespan.setTextContent(title+":");
				
				Element valuespan = doc.createElement("xhtml:span");
				valuespan.setAttribute("class", "value");
				valuespan.setTextContent(v.asPrimitiveValue().getValue());
				
				div.appendChild(titlespan);
				div.appendChild(valuespan);
			}
		}
	}
	
}
